﻿//集中Ajax
function AJAX(url, param, func, method, useLoading, async) {
    var asyncbool = typeof (async) == "undefined" ? true : async;
    if (!method) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }
   if(method=="GET"&&JSON.stringify(param)=="{}"){
       param=undefined;
   }
    $.ajax({
        url: "http://localhost:8080"+url,
        type: method || "POST",
        dataType: (method != "POST") ? 'html' : "JSON",
        contentType: (method != "POST") ? "text/html;charset=utf-8" : "application/json;charset=utf-8",
        data: JSON.stringify(param),
        async: asyncbool,

        success: function (o, status, response) {
            if (o && o["Message"]) {
                if (o["Message"] == 401 || o["Message"] == 403) {
                    var rxt_key = $.cookie("RTX_KEY");
                    if (rxt_key) {
                        JSBridge.closeWindow();
                    } else {
                        window.location.href = "/Account/LogOff"
                    }
                } else {
                  window.parent.postMessage(
                    { funname: 'error', msg: "Request exception, code:" + o["Message"] },
                    location.origin
                  )
                }
                return;
            }
            //错误弹出提示
            if (o && o['errorCode']) {
                if (o['param']) {
                    var text = T(o['errorCode'], o.d.param);
                         window.parent.postMessage(
                    { funname: 'error', msg: text },
                    location.origin
                  )
                }
                else {
                  window.parent.postMessage(
                    { funname: 'error', msg: o['errorCode'] },
                    location.origin
                  )
                    //ShowError(o['errorCode']);
                }
                return;
            }
            //调转登录页面
            if (o && o['errorCode']) {
                window.location.href = o['promptCode'];
                return;
            }
            //调转到提示页面
            if (o && o['promptCode']) {
                window.location.href = o['promptCode'];
                return;
            }
            func(o);//WebService返回带有d
        },
        error: function (e) {
            if (e.status == 0) return;

            if (e.status == 999) {//登陆超时
              window.parent.postMessage(
                { funname: 'error', msg: '登陆超时' },
                location.origin
              )
                if (window.parent) {
                    setTimeout('window.parent.location.href="/";', 2000);
                } else {
                    setTimeout('location.href="/";', 2000);
                }
            } else if (e.status == 998) {
              window.parent.postMessage(
                { funname: 'error', msg: e.responseText },
                location.origin
              )
            }
            else {
              window.parent.postMessage(
                { funname:  'error', msg: '请求状态: ' + e.status + '\n错误信息: ' + e.statusText },
                location.origin
              )
            }
        },
      beforeSend: function (xhr) {
        var sessionid = "Authorization";
        xhr.setRequestHeader(sessionid,"Bearer "+ getCookie("AuthToken"));
            if (useLoading != false)
                Loading();
        },
        complete: function (a, b, c) {
            if (useLoading != false)
                Loading('close');
        }
    });
};
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg))
    return unescape(arr[2]);
  else
    return null;
};
//调用API接口
function AJAXAPI(url, param, func, method, useLoading, async) {
   // var Interfaceurl = '/api/WInterface/AjaxPost';
   // var data = { apiurl: url, param: JSON.stringify(param) };
    AJAX(url, param, func, method, useLoading, async);
}
//动态加载js文件的函数
function loadJs(url, fuc) {
    if (window[url] == undefined || window["jquery.photoClip.js"] == false) {
        if (url.indexOf("/") == 0) {
            url = "http://" + window.location.host + url;
        }
    AJAX(url, {}, function (d) {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.text = d;
        document.getElementsByTagName('head')[0].appendChild(script);
        fuc();
    }, "GET");
    }else
    {
        fuc();
    }
}
//动态加载css文件的函数
function loadCss(url) {
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}
//当前语言 CN  EN  TW
function SetLang(code) {
    code = code ? code : 'CN';
    $.cookie('Lang', code, {
        path: '/'
    });
}
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return "";
}
//获取浏览器语言
function GetBrowserLang() {
    if (navigator.appName == 'Netscape') // firefox、chrome
        var lang = navigator.language;
    else // ie、opera
        var lang = navigator.browserLanguage;

    if (lang.indexOf('zh') > -1)
        return 'CN';

    if (lang.indexOf('en') > -1)
        return 'EN';

    if (lang.indexOf('de') > -1)
        return 'DE';

    if (lang.indexOf('fr') > -1)
        return 'FR';

    if (lang.indexOf('es') > -1)
        return 'ES';

    if (lang.indexOf('it') > -1)
        return 'IT';

    return 'EN';
}
//读取Html
function Load_Html(url, func) {
    var arr = url.split('_');
    url = "/" + arr[0] + "/" + arr[1];
    AJAXAPI(url, $.nd(), func, "GET");
}

function g_loading(cmd) {
    if (cmd != "close" && $(".g_loading").length == 0) {
        $('<div class="g_overlay" byloading="true"></div><div class="g_loading" style="display:none"><div class="sn-html5-loadmore"><div class="sn-html5-loading"><div class="blueball"></div><div class="orangeball"></div></div></div></div>').appendTo('body');
        $('.g_loading').show();
        $(".g_overlay").bind("click touchstart", function (e) {
            e.preventDefault();
            return;
        });
    }

    if (cmd == "close") {
        $('.g_loading').hide(0, function () {
            $('.g_overlay[byloading]').remove(); $(this).remove();
        });
    }
};

function Loading(cmd) {
    var i = $('body').data('loading_times') || 0;
    if (cmd != 'close') {
        if (i == 0) {
            $('<div class="overlay" byloading="true"></div><div class="loading" style="display:none"><div class="sn-html5-loadmore"><div class="sn-html5-loading"><div class="blueball"></div><div class="orangeball"></div></div></div></div>').appendTo('body');
            $('.loading').show(0);
        }
        $('body').data('loading_times', ++i);
    } else {
        i = 0;
        $('body').data('loading_times', 0);
    }
    if (i <= 0) {
        $('.loading').hide(0, function () {
            $('.overlay[byloading]').remove(); $(this).remove();
        });
    }
}

//提示基础
function _Show(msg, type) {
    var show_func = $('body').data('show_func');
    var show_Timeout = $('body').data('show_Timeout');
    if (show_func && show_Timeout) {
        show_func();
        clearTimeout(show_Timeout);
    }

    var div = $('<div class="' + type + '">' + msg + '</div>').appendTo(window.parent.document.body);
    show_func = function () {
        div.remove()
    };
    show_Timeout = setTimeout(show_func, 3600);
    $('body').data({
        show_func: show_func, show_Timeout: show_Timeout
    });
}


function ShowTip(msg, ismult) {
    Loading('close');
    var tip_width = $(window).width();
    if (tip_width > 320) {
        tip_width = 320;
    } else {
        tip_width = 260;
    }
    parent.layer.open({
        type: 1,
        title: [
        //'提示',
              window.Lang['text_app_tips'],
              'text-align: left;padding-left: 12px;'
        ],
        content: '<div class="layui-content" style="width: ' + tip_width + 'px; height: 80px;"><div class="layui-info"><i class="success"></i><span style="display: inline-block; line-height: 20px; width: calc(100% - 40px); vertical-align: middle;">' + msg + '</span></div></div><div class="layui-footer"><button type="button" class="btn btn-primary save">' + window.Lang['text_wmp_confirm'] + '</button></div>',
        animate: 'bounceInDown',
        success: function (layero) {
            dialog = $(layero);
            var index = dialog.attr("index");
            setTimeout(function () {
                parent.layer.close(index);
            }, 1000 * 10);
            dialog.find(".save").click(function () {
                parent.layer.close(index);
            });
        }
    });
}
function ShowError(msg, ismult) {
    Loading('close');
    parent.dialogOnlyConfirm(msg);
}
//设定弹出页的尺寸(有搜索框)
function dialogResize(obj, _w, _h, _t, hasScroll) {
    var layui_content = obj.find(".layui-content");
    var win_width = $(window).width();
    var win_height = $(window).height();
    var body_height = win_height - 106;
    if (win_width > 768) {
        if (_t) {
            body_height = body_height - _t;
        }
        if (_w && win_width >= _w) {
            layui_content.width(_w);
        } else {
            layui_content.width(win_width);
        }
        if (_h && body_height >= _h) {
            layui_content.height(_h);
        } else {
            layui_content.height(body_height);
        }

    } else {
        layui_content.width(win_width).height(body_height);
        if (!hasScroll) {
            layui_content.css({
              ///  "overflow-y": "hidden"
            });
            obj.bind("touchmove", function (e) {
                e.preventDefault();
            });
        }
        var layermchild = obj.find(".layui-m-layerchild");
        layermchild.addClass("layerfixed");
    }
}

//确认提示关闭
function dialogInfoClose(msg, okBtn) {
    var tip_width = $(window).width();
    if (tip_width > 320) {
        tip_width = 320;
    } else {
        tip_width = 260;
    }
    parent.layer.open({
        type: 1,
        title: [
          //'提示',
          window.Lang['text_app_tips'],
          'text-align: left;padding-left: 12px;'
        ],
        content: '<div class="layui-content" style="width: ' + tip_width + 'px; height: 80px;"><div class="layui-info"><i class="success"></i><span style="display: inline-block; line-height: 20px; width: calc(100% - 40px); vertical-align: middle">' + msg + '</span></div></div><div class="layui-footer"><button type="button" class="btn btn-primary save">' + window.Lang['text_wmp_confirm'] + '</button></div>',
        animate: 'bounceInDown',
        closeBtn: 0,
        shadeClose: false,
        success: function (layero) {
            dialog = $(layero);
            var index = dialog.attr("index");
            var win_width = $(window).width();
            //确定提交
            dialog.find(".save").click(function () {
                if (okBtn != undefined) {
                    okBtn(index);
                } else {
                    if (win_width > 768) {
                        window.close();
                        parent.layer.close(index);
                    } else {
                        window.location.href = "/Home/Manage";
                    }
                }
            });
        }
    });
}
//确认提示关闭
function dialogConfirmBox(msg, okBtn, cancelBtn) {
    var tip_width = $(window).width();
    if (tip_width > 320) {
        tip_width = 320;
    } else {
        tip_width = 260;
    }
    parent.layer.open({
        type: 1,
        title: [
          //'提示',
          window.Lang['text_app_tips'],
          'text-align: left;padding-left: 12px;'
        ],
        content: '<div class="layui-content" style="width: ' + tip_width + 'px; height: 80px;"><div class="layui-info"><i class="confirm" style="float: left"></i><span style="display: inline-block; line-height: 20px; width: calc(100% - 40px); vertical-align: middle">' + msg + '</span></div></div><div class="layui-footer"><button type="button" class="btn btn-default cancel">' + window.Lang['text_app_cancel'] + '</button><button type="button" class="btn btn-primary save">' + window.Lang['text_wmp_confirm'] + '</button></div>',
        animate: 'bounceInDown',
        success: function (layero) {
            dialog = $(layero);
            var index = dialog.attr("index");
            //取消
            dialog.find(".cancel").click(function () {
                if (cancelBtn != undefined && cancelBtn != null) {
                    cancelBtn(index);
                }
                if (parent.layer!=undefined)
                parent.layer.close(index);
            });
            //确定提交
            dialog.find(".save").click(function () {
                okBtn(index);
            });
        }
    });
}

function dialogOnlyConfirm(msg, okBtn) {

    var tip_width = $(window).width();
    if (tip_width > 320) {
        tip_width = 320;
    } else {
        tip_width = 260;
    }
    parent.layer.open({
        type: 1,
        title: [
          window.Lang['text_app_tips'],
          'text-align: left;padding-left: 12px;'
        ],
        content: '<div class="layui-content" style="width: ' + tip_width + 'px; height: 80px;"><div class="layui-info"><i class="confirm" style="float: left"></i><span style="display: inline-block; line-height: 20px; width: calc(100% - 40px); vertical-align: middle">' + msg + '</span></div></div><div class="layui-footer"><button type="button" class="btn btn-primary save">' + window.Lang['text_wmp_confirm'] + '</button></div>',
        animate: 'bounceInDown',
        success: function (layero) {
            dialog = $(layero);
            var index = dialog.attr("index");
            setTimeout(function () {
                parent.layer.close(index);
            }, 1000 * 10);
            dialog.find(".save").click(function () {
                if ($.isFunction(okBtn)) {
                    okBtn(index);
                }
                parent.layer.close(index);
            });
        }
    });
}

//判断是否ie浏览器
function isIE() {
    var userAgent = navigator.userAgent.toLowerCase();
    return ((/msie/.test(userAgent) && !/opera/.test(userAgent)) || /trident/.test(userAgent));
};
//判断似乎火狐浏览器
function isFiefox() {
    var userAgent = navigator.userAgent.toLowerCase();
    return (/mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent));
};

function iScrollClick() {
    if (/iPhone|iPad|iPod|Macintosh/i.test(navigator.userAgent)) return false;
    if (/Chrome/i.test(navigator.userAgent)) return (/Android/i.test(navigator.userAgent));
    if (/Silk/i.test(navigator.userAgent)) return false;
    if (/Android/i.test(navigator.userAgent)) {
        var s = navigator.userAgent.substr(navigator.userAgent.indexOf('Android') + 8, 3);
        return parseFloat(s[0] + s[3]) < 44 ? false : true
    }
}

//获取右框架宽度，用于设置
function maxFrameWidth() {
    return $('body').width() - 220;
}
//确认提示
function Confirm(msg, okBtn, cancelFun) {
    parent.layer.open({
        title: window.Lang['text_app_tips'],
        content: '<div class="layui-tip">' + msg + '</div>',
        btn: [window.Lang['text_app_confirm'], window.Lang['text_app_cancel']],
        yes: function (index) {
            if ($.isFunction(okBtn)) {
                okBtn(index);
            }
            parent.layer.close(index);
        },
        no: function () {
            if ($.isFunction(cancelFun)) {
                cancelFun();
            }
        }
    });
}
//确认提示
function SuccessConfirm(fun) {
    var device = checkterminal();
    if (device == "PC") {
        Loading('close');
        if (window.LangType == 'CN') {
            layer.open({
                title: '<span>提示<span>',
                skin: 'layui-layer-molv',
                content: '<div class="layui-tip-line"><i class="tip_icon glyphicon glyphicon-info-sign"></i><span class="tip_info">操作成功<span></div>',
                btn: ['确定'],
                shadeClose: false,
                yes: function (index) {

                    if (typeof (fun) == "function") {
                        fun(index);
                        layer.closeAll();
                    } else {
                        closewin();
                    }
                }
            });
        } else {
            layer.open({
                title: '<span>Tips<span>',
                skin: 'layui-layer-molv',
                content: '<div class="layui-tip-line"><i class="tip_icon glyphicon glyphicon-info-sign"></i><span class="tip_info">Successfully Operated<span></div>',
                btn: ['Confirm'],
                shadeClose: false,
                yes: function (index) {
                    //dialog = $(layero);
                    //var index = dialog.attr("index");
                    if (typeof (fun) == "function") {
                        fun(index);
                        layer.closeAll();
                    } else {
                        closewin();
                    }
                }
            });
        }
    } else {
        window.location.href = "/Prompt/Success?type=action&ref=" + document.referrer;
    }
}
//关闭当前页面
function closewin() {
    if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1) {
        window.location.href = "/";
        window.close();
    } else {
        window.opener = null;
        window.open("", "_self");
        window.close();
    }
}
//提示
function layerTip(msg) {
    layer.open({
        content: msg
        , skin: 'msg'
        , time: 2
    });
}

//清除空白,参数一:父元素开始查找,排除参数二
function TrimAll(T, unTrim) {
    $(T).find('input').not(unTrim).each(function () {
        $(this).val($.trim($(this).val()));
    });
}
//如值是NULL,undefined返回空
function TrimNull(value) {
    if (value == null || value == undefined) {
        return '';
    }
    return value;
}
//生成GUID
function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
//获取GUID
function getGUID(value) {
    if (value == undefined || value == null || value == "")
        return null;
    if (value == "0")
        return "00000000-0000-0000-0000-000000000000";
    if (isGUID(value)) {
        return value;
    } else {
        return null;
    }
}
//替换所有字符
function replaceALLStr(str, key, value) {
    var re = new RegExp(key, "g");
    return str.replace(re, value);
}
//是否GUID
function isGUID(value) {
    var reg = /^\w{8}-(\w{4}-){3}\w{12}$/;
    return reg.test(value);
}
//是否整数
function isInteger(value) {
    if (value == undefined || value == null || value == "")
        return false;
    return value ? (value.toString().match(/^\d+$/) ? true : false) : false;
}
//是否数字
function isNumber(value) {
    if (value == undefined || value == null || value == "")
        return false;
    return value ? (value.toString().match(/^[+-]?\d+(\.\d+)?$|^$|^(\d+|\-){7,}$/) ? true : false) : false;
}
//是否邮箱
function isEmail(value) {
    var p = /^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$/;
    return p.test(value);
}

//通过设备 展示标签
function ShowPageContorl(terminal) {
    terminal = terminal || _myterminal
    $(".row_all_gird").hide();
    if (terminal == "PC") {
        $(".row_wx_gird").show();
    } else {
        $(".row_pc_gird").show();
    }
}

//根据Code取权限
function getFunctionByCode(code, list) {
    var flag = undefined;
    list = list || _functionList;
    $(list).each(function () {
        if (this.code == code) {
            flag = this;
            return false;
        } else if (this.children) {
            $(this.children).each(function () {
                if (this.code == code) {
                    flag = this;
                } else if (this.children) {
                    $(this.children).each(function () {
                        if (this.code == code) {
                            flag = this;
                        } else if (this.children) {
                            $(this.children).each(function () {
                                if (this.code == code) {
                                    flag = this;
                                } else if (this.children) {
                                    $(this.children).each(function () {
                                        if (this.code == code) {
                                            flag = this;
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            });
        }
    });
    return flag
}
//准备增删改查权限-清除操作
function ClearNoRight(right) {
    try {
        var list = right.trim();
        //查看、添加、编辑、删除、审核、导出、排单、验货、废止,审批，驳回，签收，扩展1，扩展2，查询路由
        $(['View', 'Add', 'Edit', 'Delete', 'Config', 'Export', 'Import', 'Approve', 'Reject', 'Sign', 'QueryRouting', 'Download', 'Upload', 'Approval', 'Print', 'Extend1', 'Extend2', 'Extend3']).each(function (i, o) {
            if (list.indexOf(o) == -1) {
                $('.' + o).parent().removeAttr('title');
                $('.' + o).remove();
            }
        });
    } catch (e) {
        //查看、添加、编辑、删除、审核、导出、排单、验货、废止
        $(['View', 'Add', 'Edit', 'Delete', 'Config', 'Export', 'Import', 'Approve', 'Reject', 'Sign', 'QueryRouting', 'Download', 'Upload', 'Approval', 'Print', 'Extend1', 'Extend2', 'Extend3']).each(function (i, o) {
            $('.' + o).parent().removeAttr('title');
            $('.' + o).remove();
        });
    }

}
//在Iframe下隐藏头部
function ClearIframeHeader() {
    var contentmain = $('#content-main', window.parent.document);
    if (contentmain.length > 0) {
        $(".ibox").addClass("ibox-frame");
    }
}

//填充下拉框    - 数组对象,  目标元素, 第一个选项文本(或false)  , id ,文本,
function FillSelect(d, target, defaultItem, vId, vText) {
    vId = vId ? vId : 'ID';
    vText = vText ? vText : 'Name';
    var options = defaultItem ? '<option value="' + defaultItem[vId] + '">' + defaultItem[vText] + '</option>' : '';
    $(d).each(function (i, o) {
        options += '<option value="' + o[vId] + '">' + o[vText] + '</option>';
    });
    $(target).html(options);
}


//创建上传工具
function CreateUploader(url, browseBtn, uploadBtn, complete) {
    _uploadObj.complete = complete;
    var id = 'f' + new Date().getTime();
    $('<iframe id="' + id + '" frameborder="no"></iframe>').css({ 'display': 'none' }).appendTo($(browseBtn).parent());
    var ifString = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><form method="post" id="form1" action="' + url + '" enctype="multipart/form-data"><input id="file" type="file" name="file" /></form></body></html>';
    (window.frames[id].document || window.frames[$('iframe').length - 1].document).writeln(ifString); // FF需要用序号，不支持id
    var doc = _uploadObj.doc = $(window.frames[id].document || window.frames[$('iframe').length - 1].document);
    doc.find('#file').change(function (e) {
        var arr = e.target.value.split('.');
        if (_uploadObj.extendNames.where('o=="' + arr[arr.length - 1] + '"').length > 0) {
            $(browseBtn).parent().parent().find('input[type=text]').val(e.target.value);
        } else {
            $([$(browseBtn).prev()[0], e.target]).val('');
            ShowError(LangMsg.file_format_support + _uploadObj.extendNames.join(','));
        }
    });
    $(browseBtn).unbind('click').click(function () {
        doc.find('#file').click();
    });
    $(uploadBtn).unbind('click').click(function () {
        if (doc.find('#file').first().val() == '')
            ShowError(Lang.please_select_file);
        else
            _uploadObj.submit();
    });

    return {
        reset: function () {
            $('#' + id).remove();
            $(browseBtn).parent().parent().find('input[type=text]').val('');
            CreateUploader(url, browseBtn, uploadBtn, complete);
        }
    };
}

var _uploadObj = {
    extendNames: ['xls', 'xlsx', 'zip', 'rar', 'jpg', 'gif'],
    doc: null,
    submit: function () {
        //loading
        Loading();
        this.doc.find('form').submit();
    }, complete: function (code) {
        //un loading

    }, download: function (url) {
        var id = 'f' + new Date().getTime();
        var ifString = '<div class="hide"><iframe id="' + id + '" name="' + id + '" frameborder="no" src="' + url + '"></iframe></div>';
        $('body').append(ifString);
    }
};

function checkterminal() {
    if ($(window).width() < 768) {
        return "MOBILE";
    }
    //平台、设备和操作系统
    var system = {
        win: false,
        mac: false,
        xll: false
    };
    //检测平台
    var p = navigator.platform;

    /**var sUserAgent = navigator.userAgent.toLowerCase();
    alert(sUserAgent);*/

    system.win = p.indexOf("Win") == 0;
    system.mac = p.indexOf("Mac") == 0;
    system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
    //跳转语句
    if (system.win || system.mac || system.xll) {//转向后台登陆页面
        return "PC";
    } else {
        return "MOBILE";
    }
}

//获得ip地理信息
function getIpAdrress() {
    $.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function () {
        alert(remote_ip_info["country"] + ',' + remote_ip_info["province"] + "省" + ',' + remote_ip_info["city"] + "市");
    });
}

//删除数组
Array.prototype.remove = function (dx) {
    if (isNaN(dx) || dx > this.length) {
        return false;
    }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i]
        }
    }
    this.length -= 1
}
//展开 收缩
function collapselink(obj) {
    var queryarea = $(obj).parents(".ibox").find(".query-area");
    if (queryarea.is(":visible")) {
        queryarea.slideUp("slow");
        $(this).find("i").attr("class", "fa fa-chevron-down");
    } else {
        queryarea.slideDown("slow");
        $(this).find("i").attr("class", "fa fa-chevron-up");
    }
}
///将日期字符串转换成固定格式的日期
String.prototype.Dateformat = function (format) {
    if (this != null || this != undefined) {
        var time_str = this.toLocaleString().replace("T", " ").replace(/-/g, "/");
        if (time_str.indexOf(".") > -1) {
            time_str = time_str.substring(0, time_str.indexOf("."));
        }
        var datetime = new Date(time_str);
        if (datetime.getFullYear() == 1900) return "";
        return datetime.Format(format);
    }
    return '';
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

$(function () {
    Fix_Android_input();

    setTimeout(function () {
        $("textarea.multy_textarea").each(function () {
            if (!$(this).is(':visible')) {
                return;
            }
            var show_width = $(this).width();
            var thisVal = $(this).val();
            var div_name = "textarea_container_" + $(this).attr("id");
            var container = $("<div id='" + div_name + "' style='width:" + show_width + "px;min-height:10px;height:auto;overflow: hidden;border:1px solid #ccc;'/>");
            container.append(thisVal);

            $("body").append(container);
            var height = $("#" + div_name).height();
            if (height > $(this).height()) {
                $(this).css("height", height + "px");
                $(this).parent().prev().css({
                    "height": height + "px", "line-height": height + "px"
                });
            }

            $("#" + div_name).remove();
        });
    }, 1000);
});

function Fix_Android_input() {
    if ($(window).width() < 768) {
        $(document).on('focus', 'input:enabled,textarea', function () {
            if ($(this).attr("class") && $(this).attr("class").indexOf("mbsc") == -1) {
                $(".navbar-fixed-bottom").css({
                    "position": ""
                });
            }
        });

        $(document).on('blur', 'input:enabled,textarea', function () {
            $(".navbar-fixed-bottom").css("position", "fixed");
        });
    }
};

var Positioin_object;
function Fix_Position(isvisible, scroll_top) {
    if (!/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        return;
    }
    if (isvisible) {
        if (!$("div.portal").is(":visible")) {
            $("div.portal").show();
        }
    } else {
        if ($("div.portal").is(":visible")) {
            $("div.portal").hide();
        }
    }

    if (scroll_top && $(window).width() < 768) {
        if (scroll_top < ($(window).height() / 2)) {
            scroll_top = 0;
        } else {
            scroll_top = scroll_top - 100;
        }

        setTimeout(function () {
            $(window).scrollTop(scroll_top);
        }, 50);
    }
};

function Fix_Layer_Close() {
    $("tr.click_item").removeClass("click_item");
    Fix_Position(true);
};

// 对中文数据进行翻译
function TranslateItem(sour) {
    return window.Lang[TrimNull(sour)] == null ? TrimNull(sour) : window.Lang[TrimNull(sour)];
}

/*将指定时间转化为北京时间*/
function ToBeiJingTime(time) {
    if (!(time instanceof Date)) {
        time = time.replace(new RegExp(/-/gm), "/");
        time = new Date(time);
    }

    if (isNaN(time.getTime())) {
        alert("传入类型错误");
        return;
    }

    var zeroTime = new Date(time.setMinutes(time.getMinutes() + new Date().getTimezoneOffset()));//utc 0
    return new Date(zeroTime.setMinutes(zeroTime.getMinutes() + 480));
};
/*将北京时间转化为设定时区时间*/
function ToSetZoneTime(time) {
    if (!(time instanceof Date)) {
        time = time.replace(new RegExp(/-/gm), "/");
        time = new Date(time);
    }

    if (isNaN(time.getTime())) {
        alert("传入类型错误");
        return;
    }
    var zeroTime = new Date(time.setMinutes(time.getMinutes() - 480));//utc 0
    var show = new Date(zeroTime.setMinutes(zeroTime.getMinutes() + userInfo.timeoffset * 60));
    return show.CultureFormat(userInfo.format);
};

Date.prototype.CultureFormat = function (formatStr) {
    var date = this;
    /*
    函数：填充0字符
    参数：value-需要填充的字符串, length-总长度
    返回：填充后的字符串
    */
    var zeroize = function (value, length) {
        if (!length) {
            length = 2;
        }
        value = new String(value);
        for (var i = 0, zeros = ''; i < (length - value.length) ; i++) {
            zeros += '0';
        }
        return zeros + value;
    };
    return formatStr.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|M{1,4}|yy(?:yy)?|([hHmstT])\1?|[lLZ])\b/g, function ($0) {
        switch ($0) {
            case 'd': return date.getDate();
            case 'dd': return zeroize(date.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][date.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][date.getDay()];
            case 'M': return date.getMonth() + 1;
            case 'MM': return zeroize(date.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][date.getMonth()];
            case 'yy': return new String(date.getFullYear()).substr(2);
            case 'yyyy': return date.getFullYear();
            case 'h': return date.getHours() % 12 || 12;
            case 'hh': return zeroize(date.getHours() % 12 || 12);
            case 'H': return date.getHours();
            case 'HH': return zeroize(date.getHours());
            case 'm': return date.getMinutes();
            case 'mm': return zeroize(date.getMinutes());
            case 's': return date.getSeconds();
            case 'ss': return zeroize(date.getSeconds());
            case 'l': return date.getMilliseconds();
            case 'll': return zeroize(date.getMilliseconds());
            case 'tt': return date.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return date.getHours() < 12 ? 'AM' : 'PM';
        }
    });
}
function ServerNewID() {
    var guid = null;
    // AJAXAPI("/api/From/GetNewGuid", {}, function (d) {
    //     if (d.success) {
    //         guid = d.data;
    //     }
    // }, undefined, undefined, false);
    return "";
}
try{
    if (window.localStorage && window.localStorage.getItem("Attachment") == "1") {
        window.localStorage.removeItem("Attachment");
        document.location.reload();
    }
}
catch(ex){}

